package com.xscr.api.service.order;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.annotation.Resource;



import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import com.rop.annotation.HttpAction;
import com.rop.annotation.IgnoreSignType;
import com.rop.annotation.NeedInSessionType;
import com.rop.annotation.ServiceMethod;
import com.rop.annotation.ServiceMethodBean;
import com.rop.response.Response;
import com.xscr.api.pojo.AddressDTO;
import com.xscr.api.pojo.ProductExtDTO;
import com.xscr.api.request.AddCartRequest;
import com.xscr.api.request.CalculateCartRequest;
import com.xscr.api.request.CommitOrderRequest;
import com.xscr.api.request.GetCartAmountRequest;
import com.xscr.api.request.GetCartRequest;
import com.xscr.api.request.GetLogisticsPriceRequest;
import com.xscr.api.request.UpdateAddressRequest;
import com.xscr.api.utils.CodeUtil;
import com.xscr.item.api.ItemService;
import com.xscr.order.api.CartService;
import com.xscr.order.api.LogisticsPriceService;
import com.xscr.order.api.OrderCouponService;
import com.xscr.order.api.OrderFormService;
import com.xscr.order.api.OrderItemCouponService;
import com.xscr.order.api.OrderItemService;
import com.xscr.order.dto.CartDto;
import com.xscr.order.dto.CartSkuDto;
import com.xscr.order.dto.CartSkuGroupDto;
import com.xscr.order.po.OrderCoupon;
import com.xscr.order.po.OrderForm;
import com.xscr.order.po.OrderItem;
import com.xscr.order.po.OrderItemCoupon;
import com.xscr.promotion.api.CouponService;
import com.xscr.promotion.api.ProRuleService;
import com.xscr.promotion.po.ProCoupon;
import com.xscr.promotion.po.ProCouponCode;
import com.xscr.promotion.po.ProCouponItem;
import com.xscr.promotion.po.ProRule;
import com.xscr.user.po.CuserAddress;
import com.xscr.user.po.User;
import com.xscr.user.service.ICuserAddressService;
import com.xscr.user.service.UserService;

@ServiceMethodBean(version = "1.0", ignoreSign = IgnoreSignType.NO)
public class CartAction {
	
	private static final Logger logger=LoggerFactory.getLogger(CartAction.class);

	@Autowired
	private CartService cartService;

	@Autowired
	private ItemService itemService;

	@Resource
	ICuserAddressService userAddressService;

	@Resource
	OrderItemService orderItemService;

	@Resource
	OrderFormService orderFormservice;

	@Resource
	UserService userService;

	@Resource
	CouponService couponService;
	
	@Resource
	LogisticsPriceService logisticsPriceService;

	@Resource
	OrderItemCouponService orderItemCouponService;
	@Resource
	OrderCouponService orderCouponService;
	@Resource
	ProRuleService proRuleService;

	/**
	 * 获取运费
	 * @param getLogisticsPriceRequest
	 * @return
	 */
	@ServiceMethod(method = "cart.getLogisticsPrice", version = "1.0", needInSession = NeedInSessionType.NO, httpAction = HttpAction.GET)
	public Response getLogisticsPrice(GetLogisticsPriceRequest getLogisticsPriceRequest) {
		Response response = new Response();
		String msg = "";

		String province = getLogisticsPriceRequest.getProvince();
		
		if(province==null||StringUtils.isBlank(province))
		{
			response.getResult().setResult("0");
			response.getResult().setMessage("参数不合法");
			return response;
		}
		
		try {
			Map<String, Object> data = new HashMap<String, Object>(5);
			BigDecimal logisticsPrice= logisticsPriceService.getLogisticsPrice(province);
			data.put("logisticsPrice", logisticsPrice);
			response.setData(data);
		} catch (Exception e) {
			logger.error("getLogisticsPrice error", e);
			response.getResult().setResult("0");
			response.getResult().setMessage("获取运费错误");
			return response;
		}
		msg = "获取运费成功";
		response.getResult().setResult("1");
		response.getResult().setMessage(msg);
		return response;
	}
	
	/**
	 * 添加购物车
	 * 
	 * @param addCartRequest
	 * @return
	 */
	@ServiceMethod(method = "cart.addToCart", version = "1.0", needInSession = NeedInSessionType.NO, httpAction = HttpAction.POST)
	public Response addToCart(AddCartRequest addCartRequest) {
		Response response = new Response();
		String msg = "";
		Long skuId = addCartRequest.getSkuId();
		Integer count = addCartRequest.getCount();
		Long userId = addCartRequest.getUserId();
		
		if(userId==null||StringUtils.isBlank(userId.toString())||skuId==null||StringUtils.isBlank(skuId.toString())||count==null)
		{
			response.getResult().setResult("0");
			response.getResult().setMessage("参数不合法");
			return response;			
		}
		
		try {

			int skuQty = 0;
			String addSku = cartService.addSku(
					Integer.valueOf(userId.toString()), userId.toString(),
					Integer.valueOf(skuId.toString()), count, 0);
			skuQty = cartService.getCountSkuQty(
					Integer.valueOf(userId.toString()), userId.toString());
			Map<String, Object> data = new HashMap<String, Object>(5);

			data.put("cartProductCount", skuQty);

			response.setData(data);
		} catch (Exception e) {
			logger.error("addToCart error", e);
			response.getResult().setResult("0");
			response.getResult().setMessage("添加购物车错误");
			return response;
		}
		msg = "添加购物车成功";
		response.getResult().setResult("1");
		response.getResult().setMessage(msg);
		return response;
	}

	/**
	 * 修改购物车
	 * 
	 * @param addCartRequest
	 * @return
	 */
	@ServiceMethod(method = "cart.updateCart", version = "1.0", needInSession = NeedInSessionType.NO, httpAction = HttpAction.POST)
	public Response updateCart(AddCartRequest addCartRequest) {
		Response response = new Response();
		String msg = "";
		Long skuId = addCartRequest.getSkuId();
		Integer count = addCartRequest.getCount();
		Long userId = addCartRequest.getUserId();
		Integer ruleId = addCartRequest.getRuleId();
		
		if(skuId==null||StringUtils.isBlank(skuId.toString())||userId==null||StringUtils.isBlank(userId.toString())||count==null)
		{
			response.getResult().setResult("0");
			response.getResult().setMessage("参数不合法");
			return response;
		}
		
		try {

			int skuQty = 0;
			cartService.updateQty(Integer.valueOf(userId.toString()),
					userId.toString(), Integer.valueOf(skuId.toString()),
					count, ruleId, 0);

			CartDto cart = cartService.getCart(Integer.valueOf(userId.toString()),
					userId.toString(), 0);
			Map<String, Object> data = new HashMap<String, Object>(5);

			data.put("cartDto", cart);

			response.setData(data);
		} catch (Exception e) {
			logger.error("updateCart error", e);
			response.getResult().setResult("0");
			response.getResult().setMessage("修改购物车错误");
			return response;
		}
		msg = "修改购物车成功";
		response.getResult().setResult("1");
		response.getResult().setMessage(msg);
		return response;
	}

	/**
	 * 删除购物车
	 * 
	 * @param addCartRequest
	 * @return
	 */
	@ServiceMethod(method = "cart.deleteCartProduct", version = "1.0", needInSession = NeedInSessionType.NO, httpAction = HttpAction.POST)
	public Response deleteCartProduct(AddCartRequest addCartRequest) {
		Response response = new Response();
		String msg = "";
		Integer count = addCartRequest.getCount();
		Long skuId = addCartRequest.getSkuId();
		Long userId = addCartRequest.getUserId();
		
		if(skuId==null||StringUtils.isBlank(skuId.toString())||userId==null||StringUtils.isBlank(userId.toString())||count==null)
		{
			response.getResult().setResult("0");
			response.getResult().setMessage("参数不合法");
			return response;
		}
		
		try {

			List<Integer> skuIdList = new ArrayList<Integer>();
			skuIdList.add(Integer.valueOf(skuId.toString()));
			cartService.deleteSkus(Integer.valueOf(userId.toString()),
					userId.toString(), skuIdList, 0);
			Integer skuQty = cartService.getCountSkuQty(
					Integer.valueOf(userId.toString()), userId.toString());
			Map<String, Object> data = new HashMap<String, Object>(5);

			data.put("cartCount", skuQty);

			response.setData(data);
		} catch (Exception e) {
			logger.error("deleteCartProduct error", e);
			response.getResult().setResult("0");
			response.getResult().setMessage("删除购物车错误");
			return response;
		}
		msg = "删除购物车成功";
		response.getResult().setResult("1");
		response.getResult().setMessage(msg);
		return response;
	}

	/**
	 * 计算购物车金额
	 * 
	 * @param getCartRequest
	 * @return
	 */
	@ServiceMethod(method = "cart.getCartAmount", version = "1.0", needInSession = NeedInSessionType.NO, httpAction = HttpAction.GET)
	public Response getCartAmount(GetCartAmountRequest getCartAmountRequest) {
		Response response = new Response();
		String msg = "";

		String skuIds = getCartAmountRequest.getSkuIds();
		Long userId = getCartAmountRequest.getUserId();
		
		if(skuIds==null||StringUtils.isBlank(skuIds)||userId==null||StringUtils.isBlank(userId.toString()))
		{
			response.getResult().setResult("0");
			response.getResult().setMessage("参数不合法");
			return response;
		}
		
		CartDto cartDto = new CartDto();
		try {
			Map<String, Object> data = new HashMap<String, Object>(5);
			List<Integer> skuIdList = new ArrayList<Integer>();
			String[] skuIdsArray = skuIds.split("-");
			for (String skuId : skuIdsArray) {
				if (skuId != null)
					skuIdList.add(Integer.parseInt(skuId));
			}
			cartDto = cartService.select(Integer.valueOf(userId.toString()), null, skuIdList, 0);
			data.put("totalAmount", cartDto.getSumPrice());
			response.setData(data);
		} catch (Exception e) {
			logger.error("getCartAmount error", e);
			response.getResult().setResult("0");
			response.getResult().setMessage("计算购物车金额错误");
			return response;
		}
		msg = "计算购物车金额成功";
		response.getResult().setResult("1");
		response.getResult().setMessage(msg);
		return response;
	}

	/**
	 * 获取购物车列表
	 * 
	 * @param addCartRequest
	 * @return
	 */
	@ServiceMethod(method = "cart.getCartList", version = "1.0", needInSession = NeedInSessionType.NO, httpAction = HttpAction.GET)
	public Response getCartList(GetCartRequest getCartRequest) {
		Response response = new Response();
		String msg = "";

		Integer page = getCartRequest.getPageCount();
		Long userId = getCartRequest.getUserId();
		
		if(userId==null||StringUtils.isBlank(userId.toString()))
		{
			response.getResult().setResult("0");
			response.getResult().setMessage("参数不合法");
			return response;
		}
		CartDto cart = null;
		try {
			
			cart = cartService.getCart(Integer.valueOf(userId.toString()),
					null, 0);
			Integer countQty = cartService.getCountQty(Integer.valueOf(userId.toString()),
					null);
			
			Map<String, Object> data = new HashMap<String, Object>(3);
			if(cart==null){
				response.getResult().setResult("1");
				response.getResult().setMessage("购物车为空");
				return response;
			}
			List<CartSkuGroupDto> skuGroup= cart.getSkuGroupDTOList();
			
			//List<ProductExtDTO> productExtList = new ArrayList<ProductExtDTO>();
			//ProductExtDTO productExt = new ProductExtDTO();
			//Integer itemId = null;
/*			List<CartSkuDto> skuListSoleOut = cart.getSkuGroupDTOList();
			for (CartSkuDto sku : skuListSoleOut) {
				SkuExtDTO skuExt = new SkuExtDTO();
				skuExt.setImgUrl(sku.getImgUrl());
				skuExt.setName(sku.getItemName());
				skuExt.setOriPrice(sku.getSkuMarketPrice());
				skuExt.setSkuId(Long.valueOf(sku.getSkuId().toString()));
				skuExt.setStock(sku.getStockQty());
				skuExt.setCurPrice(sku.getPrice());
				itemId = sku.getItemId();
				List<PromotionDTO> promotionList = new ArrayList<PromotionDTO>();
				List<ProRule> ruleList = sku.getProRuleList();
				for (ProRule rule : ruleList) {
					PromotionDTO promotion = new PromotionDTO();
					promotion.setDesc(rule.getRuleContent());
					promotion.setPromotionId(Long.valueOf(rule.getRuleId()
							.toString()));
					if ("RULE_FULL_CUT".equals(rule.getType()))
						promotion.setType(0);
					if ("RULE_FULL_GIFT".equals(rule.getType()))
						promotion.setType(1);
					if ("RULE_DISCOUNT".equals(rule.getType()))
						promotion.setType(2);
					promotionList.add(promotion);
				}
				skuExt.setPromotionList(promotionList);
				productExt.setSkuExt(skuExt);
			}
			productExt.setCount(skuListSoleOut.size());
			productExt.setProductId(Long.valueOf(itemId));
			productExtList.add(productExt);*/
			data.put("productList", skuGroup);
			data.put("cartCount", countQty);
			data.put("totalAmount", cart.getSumPrice());

			response.setData(data);
		} catch (Exception e) {
			logger.error("getCartList error", e);
			response.getResult().setResult("0");
			response.getResult().setMessage("获取购物车列表错误");
			return response;
		}
		msg = "获取购物车列表成功";
		response.getResult().setResult("1");
		response.getResult().setMessage(msg);
		return response;
	}

	/**
	 * 结算
	 * 
	 * @param calculateCartRequest
	 * @return
	 */
	@ServiceMethod(method = "cart.calculateCart", version = "1.0", needInSession = NeedInSessionType.NO, httpAction = HttpAction.GET)
	public Response calculateCart(CalculateCartRequest calculateCartRequest) {
		Response response = new Response();
		String msg = "";

		// List<String> skuList= calculateCartRequest.getSkuList();
		String skuIds = calculateCartRequest.getSkuIds();
		Integer skuIdPromptlyBuy = calculateCartRequest.getSkuIdPromptlyBuy();
		Integer qtyPromptlyBuy = calculateCartRequest.getQtyPromptlyBuy();
		Integer promptlyBuy = calculateCartRequest.getPromptlyBuy();
		Long userId = calculateCartRequest.getUserId();
		
		if(userId==null||StringUtils.isBlank(userId.toString()))
		{
			response.getResult().setResult("0");
			response.getResult().setMessage("参数不合法");
			return response;
		}
		
		try {

			Map<String, Object> data = new HashMap<String, Object>(5);

			AddressDTO address = new AddressDTO();
/*			List<CuserAddress> userAddresslist = userAddressService
					.selectUserAddressList(Integer.valueOf(userId.toString()));*/
			List<CuserAddress> userAddresslist =userAddressService.list(Integer.valueOf(userId.toString()));
			if (userAddresslist != null && userAddresslist.size() > 0) {
				for (CuserAddress addr : userAddresslist) {
/*					if (addr.getIsDefault() == 1) {*/
						address.setAddressId(addr.getId());
						//address.setAreaId(Long.valueOf(addr.getAreaCode()));
						address.setAreaName(addr.getArea());
						//address.setCityId(Long.valueOf(addr.getCity()));
						address.setCityName(addr.getCity());
						address.setDetailAddress(addr.getAddress());
						address.setIsDefault(Boolean.valueOf(addr
								.getIsDefault().toString()));
						//address.setProvinceId(Long.valueOf(addr.getProvince()));
						address.setProvinceName(addr.getProvince());
						address.setReceiveMb(addr.getMobile());
						User user = userService.selectByUserId(addr.getcUserId());
						address.setReceiverName(user.getAccountName());
						break;
/*					}*/
				}
			}
			List<Integer> skuNewList = new ArrayList<Integer>();
			String[] skuIdsArray = skuIds.split("-");
			for (String skuId : skuIdsArray) {
				if (skuId != null)
					skuNewList.add(Integer.parseInt(skuId));
			}

			/*
			 * StringBuffer sb=new StringBuffer(""); for(String sku: skuList) {
			 * skuNewList.add(Integer.valueOf(sku)); sb.append(sku+"-"); }
			 */

			CartDto cart = null;
			// 立即购买
			if (promptlyBuy == 1) {
				List<CartSkuDto> CartSkuDtoList = cartService.addSkuPromptly(
						Integer.valueOf(userId.toString()), skuIdPromptlyBuy,
						qtyPromptlyBuy, 0);
				cart = cartService.grouping(CartSkuDtoList, 0);
			} else {
				cart = cartService.select(Integer.valueOf(userId.toString()),
						userId.toString(), skuNewList, 0);
			}
			if (cart == null)
				cart = new CartDto();

			List<Map<String, Object>> enableUse = new ArrayList<Map<String, Object>>();
			List<Map<String, Object>> unenableUse = new ArrayList<Map<String, Object>>();
			List<Map<String, Object>> enableUseCodeAllScope = couponService
					.listEnableUseByScope(Integer.valueOf(userId.toString()), 1);
			List<Map<String, Object>> enableUseCodeUnAllScope = couponService
					.listEnableUseByScope(Integer.valueOf(userId.toString()), 0);

			for (Map<String, Object> map : enableUseCodeAllScope) {
				int couponType = Integer.parseInt(map.get("coupon_type") + "");
				Date startTime = (Date) map.get("startTime");
				if (couponType == 0
						&& new Date().getTime() > startTime.getTime()) {
					enableUse.add(map);
				} else if (couponType == 1) {
					if (new Date().getTime() > startTime.getTime()
							&& cart.getSumPrice().doubleValue() > Double
									.parseDouble(map.get("startFee") + "")) {
						enableUse.add(map);
					} else {
						unenableUse.add(map);
					}
				}
			}

			for (Map<String, Object> map : enableUseCodeUnAllScope) {
				int couponType = Integer.parseInt(map.get("coupon_type") + "");
				int couponId = Integer.parseInt(map.get("coupon_id") + "");
				double startFee = Double.parseDouble(map.get("startFee") + "");
				Date startTime = (Date) map.get("startTime");
				List<ProCouponItem> couponItemList = couponService
						.listByCouponId(couponId);

				if (new Date().getTime() > startTime.getTime()
						&& this.isAbleUseCoupon(couponItemList, cart,
								couponType, startFee)) {
					enableUse.add(map);
				} else {
					unenableUse.add(map);
				}
			}

			data.put("skuIds", skuIds);
			data.put("enableUse", enableUse);
			data.put("unenableUse", unenableUse);

			data.put("defaultAddress", address);
			data.put("totalAmount", cart.getSumPrice());
			data.put("productAmount", cart.getSumDomesticPrice());
			data.put("transAmount", cart.getTransferPrice());
			data.put("promotionAmount",
					cart.getFullCutPrice().add(cart.getDiscountPrice()));
			data.put("availableCouponCount", 0);

			response.setData(data);
		} catch (Exception e) {
			logger.error("calculateCart error", e);
			response.getResult().setResult("0");
			response.getResult().setMessage("结算错误");
			return response;
		}

		msg = "结算成功";
		response.getResult().setResult("1");
		response.getResult().setMessage(msg);
		return response;
	}

	private boolean isAbleUseCoupon(List<ProCouponItem> couponItemList,
			CartDto cart, int couponType, double startFee) {
		boolean isAbleUseCoupon = false;
		if (couponItemList == null || couponItemList.size() == 0
				|| cart.getSkuGroupDTOList() == null
				|| cart.getSkuGroupDTOList().size() == 0)
			return isAbleUseCoupon;
		List<CartSkuGroupDto> cartSkuGroupDtoList = cart.getSkuGroupDTOList();

		Set<Integer> set = new HashSet<Integer>();
		for (ProCouponItem proCouponItem : couponItemList) {
			set.add(proCouponItem.getSkuId());
		}
		double maxPrice = 0;
		for (CartSkuGroupDto dtoCartSkuGroupDto : cartSkuGroupDtoList) {

			for (CartSkuDto dto : dtoCartSkuGroupDto.getSkuList()) {

				if (set.contains(dto.getSkuId())) {
					maxPrice += dto.getPromotionPrice().doubleValue();
					if (couponType == 1)
						return true;
				}
			}
		}
		if (couponType == 2 && maxPrice > startFee)
			return true;
		return isAbleUseCoupon;
	}

	/**
	 * 提交订单
	 * 
	 * @param commitOrderRequest
	 * @return
	 */
	@ServiceMethod(method = "cart.commitOrder", version = "1.0", needInSession = NeedInSessionType.NO, httpAction = HttpAction.POST)
	public Response commitOrder(CommitOrderRequest commitOrderRequest) {
		Response response = new Response();
		String msg = "";

		//Long couponId = commitOrderRequest.getCouponId();
		String message = commitOrderRequest.getMessage();
		Integer payWay = commitOrderRequest.getPayWay();
		// List<String> skuList= commitOrderRequest.getSkuIdList();
		String skuIds = commitOrderRequest.getSkuIds();
		Long userId = commitOrderRequest.getUserId();
		Long addressId = commitOrderRequest.getAddressId();
		Integer useCouponCodeId = commitOrderRequest.getUseCouponCodeId();
		Integer skuIdPromptlyBuy = commitOrderRequest.getSkuIdPromptlyBuy();
		Integer qtyPromptlyBuy = commitOrderRequest.getPromptlyBuy();
		Integer promptlyBuy = commitOrderRequest.getPromptlyBuy();
		
		if(userId==null||StringUtils.isBlank(userId.toString())||addressId==null||StringUtils.isBlank(addressId.toString()))
		{
			response.getResult().setResult("0");
			response.getResult().setMessage("参数不合法");
			return response;
		}
		
		try {

			CuserAddress userAddress = userAddressService.getUserAddress(addressId);
			//CuserAddress userAddress = userAddressService.selectById(addressId);
			if (userAddress == null) {
				response.getResult().setResult("0");
				response.getResult().setMessage("用户地址为空");
				return response;
			}

			OrderForm orderForm = new OrderForm();
			orderForm.setCreateTime(new Date());
			orderForm.setUserId(Integer.valueOf(userId.toString()));
			orderForm.setOrderCode(CodeUtil.getXSCROrderCode());
			orderForm.setReceiveUserName(userAddress.getRecipient());
			orderForm.setTel(userAddress.getProvince());
			orderForm.setProvince(userAddress.getProvince());
			orderForm.setCity(userAddress.getCity());
			orderForm.setReceiptArea(userAddress.getArea());
			orderForm.setAddress(userAddress.getAddress());
			orderForm.setPostcode(userAddress.getPostCode());
			orderForm.setAddressId(Integer.valueOf(addressId.toString()));
			orderForm.setNeedInvoice(1);
			orderForm.setInvoiceType(1);
			orderForm.setOrderStatus(1);
			/*
			 * if(needInvoice==1){ orderForm.setInvoiceTitle(invoiceTitle); }
			 */
			orderForm.setUserComment(message);
			orderForm.setUserId(Integer.valueOf(userId.toString()));

			List<Integer> skuNewList = new ArrayList<Integer>();
			String[] skuIdsArray = skuIds.split("-");
			for (String skuId : skuIdsArray) {
				if (skuId != null)
					skuNewList.add(Integer.parseInt(skuId));
			}

			/*
			 * StringBuffer sb=new StringBuffer(""); for(String sku: skuList) {
			 * skuNewList.add(Integer.valueOf(sku)); sb.append(sku+"-"); }
			 * skuIds=sb.toString();
			 */

			CartDto cart = null;
			if (promptlyBuy == 1) {
				List<CartSkuDto> CartSkuDtoList = cartService.addSkuPromptly(
						Integer.valueOf(userId.toString()), skuIdPromptlyBuy,
						qtyPromptlyBuy, 0);
				cart = cartService.grouping(CartSkuDtoList, 0);
			} else {
				if (skuNewList.size() == 0)
				{
					response.getResult().setResult("0");
					response.getResult().setMessage("sku列表为空");
					return response;
				}
				cart = cartService.select(Integer.valueOf(userId.toString()),
						null, skuNewList, 0);
			}

			// cartService.select(Integer.valueOf(userId.toString()),
			// userId.toString(), skuNewList,0 );

			orderForm.setDiscountPrice(cart.getDiscountPrice());

			User user = userService.selectByUserId(Integer.valueOf(userId
					.toString()));
			if (user != null) {
				orderForm.setName(user.getAccountName());
				orderForm.setUserName(user.getLoginName());
				orderForm.setPhoneNumber(user.getPhone());
			}
			orderForm.setPrice(cart.getSumPrice());

			// 是否使用优惠券
			ProCouponCode proCouponCode = null;
			ProCoupon proCoupon = null;
			BigDecimal newPrice = null;

			if (useCouponCodeId != -1)
				proCouponCode = couponService
						.selectByPrimaryKeyProCouponCode(useCouponCodeId);
			if (proCouponCode != null)
				proCoupon = couponService
						.selectByPrimaryKeyProCoupon(proCouponCode
								.getCouponId());

			// 优惠券的金额
			String couponAlias = "代金券";
			double couponPrice = 0;
			if (proCoupon != null) {
				// 代金券
				if (proCoupon.getCouponType() == 0) {
					couponPrice = proCoupon.getCouponAmount().doubleValue();
					orderForm.setCouponPrice(proCoupon.getCouponAmount());
					newPrice = orderForm.getPrice().subtract(
							proCoupon.getCouponAmount());
					couponAlias = "代金券" + proCoupon.getCouponAmount() + "元";
				} else if (proCoupon.getCouponType() == 1) {// 满减券
					orderForm.setCouponPrice(proCoupon.getReduceAmount());
					couponPrice = proCoupon.getReduceAmount().doubleValue();
					newPrice = orderForm.getPrice().subtract(
							proCoupon.getReduceAmount());
					couponAlias = "满减券" + proCoupon.getReduceAmount() + "元";
				}

				if (newPrice.doubleValue() < 0) {
					orderForm.setPaidPrice(new BigDecimal(0));
				} else {
					orderForm.setPaidPrice(newPrice);
				}
				proCouponCode.setUseTime(new Date());
				proCouponCode.setUserId(Integer.valueOf(userId.toString()));
				proCouponCode.setIsUse((byte) 1);
				proCouponCode.setIsExpire((byte) 0);
				couponService.updateByPrimaryKeySelective(proCouponCode);
			} else {
				orderForm.setPaidPrice(orderForm.getPrice());
			}

			int hasRule = 0;
			java.util.Calendar calendar = Calendar.getInstance();
			if (cart.isHasRule()) {
				hasRule = 1;
				calendar.add(Calendar.MINUTE, 30);
			} else {
				calendar.add(Calendar.MONTH, 1);
			}
			orderForm.setPayTimeLimit(calendar.getTime());

			if (orderForm.getPaidPrice().doubleValue() == 0)
				orderForm.setOrderStatus(3);
			int orderId = orderFormservice.saveOrUpdate(orderForm);

			// 优惠券记录 以便于订单最终支付查询
			if (proCoupon != null) {
				OrderCoupon orderCoupon = new OrderCoupon();
				orderCoupon.setCouponCode(proCouponCode.getCouponCode());
				orderCoupon.setOrderId(orderId);
				orderCoupon.setSkuIds(skuIds);
				orderCoupon.setEndTime(proCoupon.getEndtime());
				orderCoupon.setRulePrice(orderForm.getCouponPrice());

				orderCouponService.insert(orderCoupon);
			}

			orderForm.setOrderId(orderId);

			Set<Integer> couponSuitSku = this.couponSuitSku(cart, proCoupon);
			// 填写优惠所对应的商品
			if (cart != null && cart.getSkuGroupDTOList() != null
					&& cart.getSkuGroupDTOList().size() > 0) {

				List<CartSkuGroupDto> cartSkuGroupDto = cart
						.getSkuGroupDTOList();
				OrderItemCoupon orderItemCoupon = null;
				ProRule proRule = null;
				for (CartSkuGroupDto dto : cartSkuGroupDto) {

					BigDecimal groupReduce = dto.getSumDomesticPrice()
							.subtract(dto.getSumPrice());

					BigDecimal groupReduceFlag = new BigDecimal(0);

					OrderItem orderItem = null;
					int orderItemId = 0;
					for (int i = 0; i < dto.getSkuList().size(); i++) {
						CartSkuDto skuDto = dto.getSkuList().get(i);

						double disCountPrice = 0;
						if (couponPrice != 0)
							disCountPrice = couponPrice
									* (skuDto.getPromotionPrice().doubleValue() / maxPrice);

						orderItem = new OrderItem();
						orderItem.setOrderId(orderId);
						orderItem.setSkuId(skuDto.getSkuId());
						orderItem.setSkuQuality(skuDto.getQty());
						orderItem.setPrice(skuDto.getPrice());
						orderItem.setSkuName(skuDto.getItemName() + "<br/>"
								+ skuDto.getSkuName());
						orderItem.setImageUrl(skuDto.getImgUrl());
						orderItem.setDiscountPrice(skuDto.getPromotionPrice());
						orderItem.setDescription(skuDto.getDescription());
						orderItem.setSkuCode(skuDto.getSkuCode());

						orderItemId = orderItemService
								.saveOrUpdateOrderItem(orderItem);

						double oldPromotionPriceSum = skuDto
								.getPromotionPrice().doubleValue()
								* skuDto.getQty();

						// 折扣
						if (skuDto.getDiscountedRuleId() != 0) {
							proRule = proRuleService.selectByPrimaryKey(skuDto
									.getDiscountedRuleId());
							if (proRule != null) {
								orderItemCoupon = new OrderItemCoupon();
								orderItemCoupon.setOrderItemId(orderItemId);
								orderItemCoupon.setSkuId(skuDto.getSkuId());
								orderItemCoupon.setCreateTime(new Date());
								orderItemCoupon.setName(proRule.getRuleAlias());
								orderItemCoupon.setPromotionId(skuDto
										.getDiscountedRuleId());
								orderItemCoupon
										.setPrice(skuDto.getPrice()
												.multiply(
														new BigDecimal(skuDto
																.getQty())));
								orderItemCoupon.setFinalPrice(new BigDecimal(
										skuDto.getPromotionPrice()
												.doubleValue()
												* skuDto.getQty()));
								orderItemCoupon
										.setDiscountPrice(orderItemCoupon
												.getPrice()
												.subtract(
														orderItemCoupon
																.getFinalPrice()));
								orderItemCoupon
										.setType(OrderItemCoupon.TYPE_DISTINCT);
								orderItemCoupon.setOrderId(orderId);
								oldPromotionPriceSum = orderItemCoupon
										.getFinalPrice().doubleValue();
								orderItemCouponService.insert(orderItemCoupon);
							}

						}

						proRule = dto.getProRule();

						// 活动优惠券的价格
						if (proRule.getRuleId().intValue() != 0
								&& dto.getIslock() == 1) {
							BigDecimal c = new BigDecimal(0);
							if (dto.getSumPrice().doubleValue() != 0) {
								c = groupReduce.divide(dto.getSumPrice(), 12,
										BigDecimal.ROUND_HALF_EVEN).multiply(
										skuDto.getSubTotalPrice());
							}

							if (dto.getSkuList().size() == 1) {
								c = groupReduce;
							} else if (i < dto.getSkuList().size() - 1) {
								groupReduceFlag = groupReduceFlag.add(c);
							} else {
								c = groupReduce.subtract(groupReduceFlag);
							}

							orderItemCoupon = new OrderItemCoupon();
							orderItemCoupon.setOrderItemId(orderItemId);
							orderItemCoupon.setCreateTime(new Date());
							orderItemCoupon.setSkuId(skuDto.getSkuId());
							orderItemCoupon.setName(proRule.getRuleAlias());
							orderItemCoupon.setPromotionId(proRule.getRuleId());
							orderItemCoupon.setPrice(skuDto.getPromotionPrice()
									.multiply(new BigDecimal(skuDto.getQty())));
							orderItemCoupon.setFinalPrice(orderItemCoupon
									.getPrice().subtract(c));
							orderItemCoupon
									.setType(OrderItemCoupon.TYPE_PROMOTION);
							orderItemCoupon.setOrderId(orderId);
							orderItemCoupon.setDiscountPrice(c);

							oldPromotionPriceSum = orderItemCoupon
									.getFinalPrice().doubleValue();

							orderItemCouponService.insert(orderItemCoupon);
						}

						// 优惠券优惠记录
						if (couponPrice != 0
								&& couponSuitSku.contains(skuDto.getSkuId())
								&& disCountPrice > 0.009) {

							orderItemCoupon = new OrderItemCoupon();
							orderItemCoupon.setOrderItemId(orderItemId);
							orderItemCoupon.setCreateTime(new Date());
							orderItemCoupon.setSkuId(skuDto.getSkuId());
							orderItemCoupon.setName(couponAlias);
							orderItemCoupon.setPromotionId(proCoupon
									.getCouponId());
							orderItemCoupon.setPrice(new BigDecimal(
									oldPromotionPriceSum));
							orderItemCoupon.setDiscountPrice(new BigDecimal(
									disCountPrice));
							orderItemCoupon
									.setFinalPrice(orderItemCoupon
											.getPrice()
											.subtract(
													orderItemCoupon
															.getDiscountPrice()));
							orderItemCoupon
									.setType(OrderItemCoupon.TYPE_COUPON);
							orderItemCoupon.setOrderId(orderId);
							orderItemCouponService.insert(orderItemCoupon);

							oldPromotionPriceSum = orderItemCoupon
									.getFinalPrice().doubleValue();
						}

						orderItem.setOrderItemId(orderItemId);
						orderItem.setFinalPrice(new BigDecimal(
								oldPromotionPriceSum));
						orderItemService.saveOrUpdateOrderItem(orderItem);
					}
					orderItemService.saveGift(dto.getGifts(), orderId);
				}

			}
			// 删除购物车
			cartService.deleteSkus(Integer.valueOf(userId.toString()),
					userId.toString(), skuNewList, 0);
			int countSkuQty = cartService.getCountSkuQty(
					Integer.valueOf(userId.toString()), userId.toString());

			// 当订单为0元时候直接减库存
			if (orderForm.getPaidPrice().doubleValue() == 0) {
				orderItemService.reduceStock(orderForm, 1);
			}

			Map<String, Object> data = new HashMap<String, Object>(5);

			data.put("orderId", orderId);
			data.put("cartCount", countSkuQty);

			response.setData(data);
		} catch (Exception e) {
			logger.error("commitOrder error", e);
			response.getResult().setResult("0");
			response.getResult().setMessage("提交订单错误");
			return response;
		}

		msg = "提交订单成功";
		response.getResult().setResult("1");
		response.getResult().setMessage(msg);
		return response;
	}

	double maxPrice = 0;

	private Set<Integer> couponSuitSku(CartDto cart, ProCoupon proCoupon) {

		Set<Integer> couponSuitSku = new HashSet<Integer>();
		Set<Integer> couponItemSku = new HashSet<Integer>();

		if (proCoupon == null || cart == null
				|| cart.getSkuGroupDTOList() == null
				|| cart.getSkuGroupDTOList().size() == 0)
			return couponSuitSku;
		List<CartSkuGroupDto> cartSkuGroupDto = cart.getSkuGroupDTOList();

		if (proCoupon.getItemScope() == 1) {
			// 全场
		} else {
			List<ProCouponItem> couponItemList = couponService
					.listByCouponId(proCoupon.getCouponId());
			if (couponItemList != null && couponItemList.size() > 0) {
				for (ProCouponItem item : couponItemList)
					couponItemSku.add(item.getSkuId());
			}
		}

		for (CartSkuGroupDto dto : cartSkuGroupDto) {
			for (CartSkuDto skuDto : dto.getSkuList()) {
				if (proCoupon.getItemScope() == 1) {
					maxPrice += skuDto.getPromotionPrice().doubleValue();
					couponSuitSku.add(skuDto.getSkuId());

				} else {
					if (couponItemSku.contains(skuDto.getSkuId())) {
						maxPrice += skuDto.getPromotionPrice().doubleValue();
						couponSuitSku.add(skuDto.getSkuId());
					}

				}
			}

		}
		// logger.info("couponSuitSku:"+couponSuitSku);
		return couponSuitSku;
	}

	/**
	 * 新增/编辑收货地址
	 * 
	 * @param updateAddressRequest
	 * @return
	 */
	@ServiceMethod(method = "cart.updateAddress", version = "1.0", needInSession = NeedInSessionType.NO, httpAction = HttpAction.POST)
	public Response updateAddress(UpdateAddressRequest updateAddressRequest) {
		Response response = new Response();
		String msg = "";

		String areaId = updateAddressRequest.getAreaId();
		String address = updateAddressRequest.getDetailAddress();
		Long addressId = updateAddressRequest.getAddressId();
		String cityId = updateAddressRequest.getCityId();
		String provinceId = updateAddressRequest.getProvinceId();
		String mobile = updateAddressRequest.getReceiveMb();
		String receiverName = updateAddressRequest.getReceiverName();
		Long userId = updateAddressRequest.getUserId();
		
		if(userId==null||StringUtils.isBlank(userId.toString()))
		{
			response.getResult().setResult("0");
			response.getResult().setMessage("参数不合法");
			return response;
		}
		
		try {
			CuserAddress cuserAddress = new CuserAddress();
			cuserAddress.setAddress(address);
			cuserAddress.setId(addressId);
			cuserAddress.setArea(areaId.toString());
			cuserAddress.setCity(cityId.toString());
			cuserAddress.setProvince(provinceId.toString());
			cuserAddress.setMobile(mobile);
			cuserAddress.setcUserId(Integer.valueOf(userId.toString()));
			cuserAddress.setRecipient(receiverName);
			cuserAddress.setIsDefault(1);
			cuserAddress.setUpdateTime(new Date());
			cuserAddress.setDelFlag(1);
			int addrId= userAddressService.saveAddress(cuserAddress);
/*			if (addressId == null)
				userAddressService.insertUserAddress(cuserAddress);
			else
				userAddressService.updateById(cuserAddress);*/
			
			CuserAddress userAddress = userAddressService.getUserAddress(Long.valueOf(addrId));
			response.setData(userAddress);
		} catch (Exception e) {
			logger.error("updateAddress error", e);
			response.getResult().setResult("0");
			response.getResult().setMessage("新增或编辑收货地址错误");
			return response;
		}

		msg = "新增或编辑收货地址成功";
		response.getResult().setResult("1");
		response.getResult().setMessage(msg);
		return response;
	}
}
